/*
 * Copyright 2008-2009 Daniel Cachapa <cachapa@gmail.com>
 * 
 * This program is distributed under the terms of the GNU General Public Licence Version 3
 * The licence can be read in its entirety in the LICENSE.txt file accompaning this source code,
 * or at: http://www.gnu.org/copyleft/gpl.html
 * 
 * This file is part of WeightWatch.
 *
 * WeightWatch is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * WeightWatch is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the WeightWatch source code. If not, see
 * <http://www.gnu.org/licenses/>.
 */

package net.cachapa.weightwatch.util;

import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import java.io.InputStream;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;


public class HttpConnector implements Runnable {
	private String url;
	private HttpConnection connection;
	private ActionListener getCompleteListener;
	private String result;
	private String errorMsg;
	
	public static final int RESULT_SUCCESS = 1;
	public static final int RESULT_ERROR = 2;

	public HttpConnector(String url) {
		this.url = url;
	}
	
	public void setActionListener(ActionListener callback) {
		this.getCompleteListener = callback;
	}

	public String getResult() {
		return result;
	}

	public String getErrorMsg() {
		return errorMsg;
	}
	
	public void get() {
		Thread getThread = new Thread(this);
        getThread.start();
	}

	public void run() {
		int resultCode;
		InputStream in = null;
		StringBuffer resultBuffer = new StringBuffer();
		try {
			connection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
			in = connection.openInputStream();
			int readChar;
			while ((readChar = in.read()) != -1) {
				resultBuffer.append((char) readChar);
			}
			resultCode = RESULT_SUCCESS;
		} catch (SecurityException se) {
			resultCode = RESULT_ERROR;
			errorMsg = "Security FAIL";
		} catch (ConnectionNotFoundException ce) {
			resultCode = RESULT_ERROR;
			errorMsg = "Couldn't establish connection";
		} catch (Exception ex) {
			resultCode = RESULT_ERROR;
			errorMsg = ex.getMessage();
			ex.printStackTrace();
		} finally {
			try {
				if (in != null) in.close();
				connection.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		result = resultBuffer.toString();
		ActionEvent ae = new ActionEvent(this, resultCode);
		getCompleteListener.actionPerformed(ae);
	}
}